import base64
import json
from flask import Flask, request, jsonify
from PIL import Image
from io import BytesIO
# from encode.encode_text import TextEncoder
from encode.encode_face import FaceRecognizer
from database.faiss_database import FaissDatabase

# 初始化Flask应用
app = Flask(__name__)

# 加载配置文件
with open('config/config.json') as f:
    config = json.load(f)

# 初始化人脸识别组件
face_recognizer = FaceRecognizer()
face_db = FaissDatabase(
    dim=128,
    index_path=config["face_data"]["bin"],
    id_map_path=config["face_data"]["npy"],
    index_type="L2",
    normalize=False
)

# 初始化商品组件
# text_encoder = TextEncoder(config["model_path"]["product_model"])
product_db = FaissDatabase(
    dim=384,
    index_path=config["product_data"]["bin"],
    id_map_path=config["product_data"]["npy"],
    index_type="IP",
    normalize=True
)

# 内存存储商品详细信息


# 辅助函数
def base64_to_image(image_base64):
    """将Base64字符串转换为PIL图像"""
    try:
        image_data = base64.b64decode(image_base64.split(",")[-1])
        return Image.open(BytesIO(image_data))
    except Exception as e:
        raise ValueError(f"无效的图片格式: {str(e)}")


# 人脸识别路由
@app.route('/api/python/register', methods=['POST'])
def register():
    try:
        data = request.json
        user_id = int(data['id'])
        image = base64_to_image(data['image'])
        if image.mode == 'RGBA':
            # 创建白色背景并合并去除Alpha通道
            background = Image.new('RGB', image.size, (255, 255, 255))
            background.paste(image, mask=image.split()[3])
            image = background
        elif image.mode not in ('RGB', 'L'):
            # 其他非RGB/L模式（如P、CMYK等）转为RGB
            image = image.convert('RGB')
        # 生成特征向量
        embedding = face_recognizer.encode(image)

        # 检查是否已存在
        if face_db.has_id(user_id):
            return jsonify({
                "code": 400,
                "message": "用户ID已存在",
                "data": {}
            })

        # 存储到数据库
        face_db.add_item(embedding, user_id)
        print(f"注册成功{user_id}")
        return jsonify({
            "code": 200,
            "message": "注册成功",
            "data": {}
        })
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": str(e),
            "data": {}
        })


@app.route('/api/python/login', methods=['POST'])
def login():
    try:
        data = request.json
        image = base64_to_image(data['image'])
        if image.mode == 'RGBA':
            # 创建白色背景并合并去除Alpha通道
            background = Image.new('RGB', image.size, (255, 255, 255))
            background.paste(image, mask=image.split()[3])
            image = background
        elif image.mode not in ('RGB', 'L'):
            # 其他非RGB/L模式（如P、CMYK等）转为RGB
            image = image.convert('RGB')
        # 生成特征向量
        embedding = face_recognizer.encode(image)

        # 搜索数据库
        results = face_db.search(embedding, top_k=1, threshold=config["face_threshold"])

        if not results:
            return jsonify({
                "code": 400,
                "message": "登录失败",
                "data": {}
            })

        return jsonify({
            "code": 200,
            "message": "登录成功",
            "data": {
                "id": int(results[0])
            }
        })
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": str(e),
            "data": {}
        })


# # 商品管理路由
# @app.route('/api/python/products', methods=['POST'])
# def add_product():
#     try:
#         data = request.json
#         product_id = int(data['product_id'])
#         description = str(data['description']).strip()
#
#         if product_db.has_id(product_id):
#             return jsonify({
#                 "code": 400,
#                 "message": "商品ID已存在",
#                 "data": {}
#             })
#
#         # 生成文本向量
#         vector = text_encoder.encode(description)
#
#         # 存储数据
#         product_db.add_item(vector, product_id)
#
#         return jsonify({
#             "code": 200,
#             "message": "商品上传成功",
#             "data": {}
#         })
#     except Exception as e:
#         return jsonify({
#             "code": 500,
#             "message": str(e),
#             "data": {}
#         })
#
#
# @app.route('/api/python/products', methods=['PUT'])
# def update_product():
#     try:
#         data = request.json
#         product_id = int(data['product_id'])
#         new_description = str(data['description']).strip()
#
#         if not product_db.has_id(product_id):
#             return jsonify({
#                 "code": 404,
#                 "message": "商品不存在",
#                 "data": {}
#             })
#
#         # 更新向量和描述
#         new_vector = text_encoder.encode(new_description)
#         product_db.update_item(new_vector, product_id)
#
#
#         return jsonify({
#             "code": 200,
#             "message": "修改成功",
#             "data": {}
#         })
#     except Exception as e:
#         return jsonify({
#             "code": 500,
#             "message": str(e),
#             "data": {}
#         })
#
#
# @app.route('/api/python/products', methods=['DELETE'])
# def delete_product():
#     try:
#         product_id = int(request.json['product_id'])
#
#         if not product_db.has_id(product_id):
#             return jsonify({
#                 "code": 404,
#                 "message": "商品不存在",
#                 "data": {}
#             })
#
#         # 删除数据
#         product_db.delete_item(product_id)
#
#         return jsonify({
#             "code": 200,
#             "message": "删除成功",
#             "data": {}
#         })
#     except Exception as e:
#         return jsonify({
#             "code": 500,
#             "message": str(e),
#             "data": {}
#         })
#
#
# @app.route('/api/python/search', methods=['GET'])
# def search_products():
#     try:
#         keyword = request.args.get('keyword', '')
#         threshold = config["search_threshold"]
#
#         # 生成查询向量
#         query_vector = text_encoder.encode(keyword)
#
#         # 执行搜索
#         results = product_db.search(query_vector, top_k=10, threshold=threshold)
#
#         return jsonify({
#             "code": 200,
#             "message": "",
#             "data": {
#                 "product_ids": [int(id) for id in results]
#             }
#         })
#     except Exception as e:
#         return jsonify({
#             "code": 500,
#             "message": str(e),
#             "data": {}
#         })


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=config["port"], debug=True)